package info.victor.login;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SignIn
 */
@WebServlet("/SignIn")
public class SignIn extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignIn() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(); //##### COOKIE #####
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		
		//We check values using REGEX
		Pattern patron = Pattern.compile("^[a-z0-9A-Z]");
		Matcher loginChecker = patron.matcher(login);	
		Matcher passwordChecker = patron.matcher(password);
		
		//Checking login value
		if (!loginChecker.find()) {
			request.setAttribute("loginerror","Login format incorrect");
			this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		
		//Checking password value
		if (!passwordChecker.find()) {
			request.setAttribute("passworderror","Password format incorrect");
			this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		
		if (login.equals("falken") && password.equals("josua")) {
			session.setAttribute("login", login); //##### COOKIE #####
			//Se manda al servlet, que lo redirecciona al JSP.
			this.getServletContext().getRequestDispatcher("/Private").forward(request, response);
		} else { //Incorrect login
			request.setAttribute("error", "Login incorrect");
			this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
	}

}
